﻿
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using System.Linq.Expressions;

namespace ServerExplorer.SharePointConnections.SharepointSiteInfo
{
    // Enables Visual Studio to discover and load this extension.
    [Export(typeof(IExplorerNodeTypeProvider))]

    // Specifies the ID for this new node type.
    [ExplorerNodeType(SharepointInfoSiteNode.SharepointInfoSiteNodeTypeId)]

    // Defines a new node type that represents a basic node info.
    internal class SharepointInfoSiteNode : IExplorerNodeTypeProvider
    {
        internal const string SharepointInfoSiteNodeTypeId = "Culture Info";

        public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
        {
            typeDefinition.IsAlwaysLeaf = false;
            typeDefinition.NodePropertiesRequested += NodePropertiesRequested;
            typeDefinition.NodeMenuItemsRequested += nodeType_NodeMenuItemsRequested;
        }

        //Retrieves properties that are displayed in the Properties window when
        //node is selected.
        private void NodePropertiesRequested(object sender, ExplorerNodePropertiesRequestedEventArgs e)
        {
            Dictionary<string, string> properties = new Dictionary<string, string>();
            object obj;
            e.Node.Annotations.TryGetValue("Info", out obj);

            System.Reflection.PropertyInfo[] propInfo = obj.GetType().GetProperties();

            foreach (System.Reflection.PropertyInfo prop in propInfo)
            {
                string PropName = prop.Name;
                string PropValue = prop.GetValue(obj, null).ToString();
                properties.Add(PropName, PropValue);
            }

            object propertySource = e.Node.Context.CreatePropertySourceObject(properties);
            e.PropertySources.Add(propertySource);
        }

        void nodeType_NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            string typeNode = e.Node.ParentNode.Text;
            if (typeNode == "Lists")
            {
                        IMenuItem menuItem = e.MenuItems.Add("Show in browser");
                        menuItem.Click += menuItem_Click;
            }
        }

        void menuItem_Click(object sender, MenuItemEventArgs e)
        {
            IExplorerNode node = (IExplorerNode)e.Owner;
            Entities.SiteInfoList value = node.Annotations.GetValue<Entities.SiteInfoList>("Info");
            Uri siteHost = node.Context.SiteUrl;
            string url = string.Format("{0}://{1}{2}{3}", siteHost.Scheme, siteHost.Host, siteHost.Port != 80 ? ":" + siteHost.Port.ToString() : "", value.Url);          System.Diagnostics.Process.Start(url);
        }
    }
}

